package com.rzico.sbl.ui.manager

import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.core.widget.TextViewCompat
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupCupboardBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CupboardData
import com.rzico.sbl.model.QRType
import com.rzico.sbl.other.showCupboardDialog
import com.rzico.sbl.ui.ScanActivity
import com.rzico.sbl.viewmodel.PickupViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.labelview.LabelView
import com.xinnuo.slimadapter.SlimAdapter

class PickupCupboardActivity : BaseActivity(R.layout.activity_pickup_cupboard) {

    private val mBinding by lazy { ActivityPickupCupboardBinding.bind(getRootView()) }

    private var mPickupId = ""
    private var mStatusIndex = -1
    private var mDialogCode: EditText? = null

    override fun getViewModel() = get<PickupViewModel>()

    override fun initData() {
        initTitle(title = "自提柜", name = "补货统计")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关自提柜信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration(bottom = 60f))
                    view.addOnScrollChanged(
                        onShow = { mBinding.cupboardBottom.bottomShow() },
                        onHide = { mBinding.cupboardBottom.bottomHide(55f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<CupboardData>(R.layout.item_pickup_cupboard) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_cupboard_name, bean.name)
                                text(R.id.item_cupboard_type, bean.typeName)
                                text(R.id.item_cupboard_num, bean.cabinetNo)
                                text(R.id.item_cupboard_count, bean.count)
                                text(R.id.item_cupboard_screen, bean.screenNo)

                                getView<View>(R.id.item_cupboard_screen_ll)
                                    .isVisible = bean.type in "AIR_TOUCh_EXTEND"
                                getView<View>(R.id.item_cupboard_logout)
                                    .isVisible = bean.type in "AIR_TOUCh_EXTEND"

                                with<LabelView>(R.id.item_cupboard_fill) {
                                    it.isVisible = bean.fillCount.intValue > 0
                                    it.text = "缺货: ${bean.fillCount}"
                                }

                                with<TextView>(R.id.item_cupboard_status) {
                                    it.setTextColor(
                                        getColorEx(
                                            when (bean.status) {
                                                "online" -> R.color.colorAccent
                                                else -> R.color.red
                                            }
                                        )
                                    )

                                    it.text = when (bean.status) {
                                        "online" -> "在线"
                                        "stop" -> "停用"
                                        else -> "离线"
                                    }
                                }

                                clicked(R.id.item_cupboard_code) {
                                    startActivityEx<PickupCodeActivity>(
                                        "title" to bean.name,
                                        "shopId" to mPickupId,
                                        "cupboardId" to bean.id
                                    )
                                }

                                clicked(R.id.item_cupboard_logout) {
                                    logoutCupboard(bean.id)
                                }

                                clicked(R.id.item_cupboard_edit) {
                                    modifyCupboard(bean, index)
                                }

                                clicked(R.id.item_cupboard_goods) {
                                    startActivityEx<PickupCupboardCodeActivity>(
                                        "pickId" to mPickupId,
                                        "cupboardId" to bean.id
                                    )
                                }

                                longClicked {
                                    deleteCupboard(bean.id, index)
                                    true
                                }
                            }
                        }
                        .attachTo(view)
                        .addHeader(
                            TextView(getIContext()).apply {
                                text = "温馨提示：长按可删除选中的自提柜"
                                setPadding(dp2px(15f), 0, 0, 0)
                                TextViewCompat.setTextAppearance(this, R.style.Font13_gray)
                            }
                        )
                }
            }

        tvRight?.oneClick {
            startActivityEx<PickupFillSummaryActivity>(
                "pickId" to mPickupId
            )
        }
    }

    override fun initListener() {
        mPickupId = intent.getExtra("pickId")

        mBinding
            .cupboardAdd
            .oneClick {
                showCupboardDialog(
                    isForced = true,
                    onScan = {
                        mDialogCode = it

                        startActivityEx<ScanActivity>(
                            "mode" to QRType.CUPBOARD,
                            "from" to "pickup"
                        )
                    },
                    onSelect = { tvType, total, screen, typeArr ->
                        showListDialog(
                            title = "请选择设备类型",
                            items = getViewModel().mTypeList.map { it.name },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index

                                typeArr[0] = getViewModel().mTypeList[index].id
                                typeArr[1] = hint

                                total.isVisible = "_EXTEND" in typeArr[0]
                                screen.isVisible = typeArr[0] in "AIR_TOUCh_EXTEND"
                                tvType.text = typeArr[1]
                            }
                        )
                    },
                    onStatus = { tvStatus, statusArr ->
                        showListDialog(
                            title = "请选择设备状态",
                            items = getViewModel().mStatusList.map { it.name },
                            index = mStatusIndex,
                            listener = { index, hint ->
                                mStatusIndex = index

                                statusArr[0] = getViewModel().mStatusList[index].id
                                statusArr[1] = hint

                                tvStatus.text = statusArr[1]
                            }
                        )
                    },
                    onSure = { name, code, id, total, screen, _ ->
                        addCupboard(name, code, id, total, screen)
                    },
                    onDismiss = { mDialogCode = null }
                )
            }

        observe<String>("cupboardList") { updateList() }

        observe<String>(QRType.CUPBOARD) { result ->
            mDialogCode?.let {
                it.setText(result)
                it.setSelection(it.text.length)
            }
        }
    }

    /**
     * 添加自提柜
     */
    private fun addCupboard(
        cupboardName: String,
        cupboardCode: String,
        cupboardType: String,
        cupboardCount: String,
        cupboardScreen: String
    ) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.mngCupAdd,
                isMultipart = true,
                params = arrayOf(
                    "shopId" to mPickupId,
                    "name" to cupboardName,
                    "cabinetNo" to cupboardCode,
                    "type" to cupboardType,
                    "count" to cupboardCount,
                    "screenNo" to cupboardScreen
                ),
                onSuccess = {
                    showToast("添加自提柜成功！")

                    updateList()
                }
            )
    }

    /**
     * 退出显示屏自提柜
     */
    private fun logoutCupboard(itemId: String) {
        showHintDialog(
            hint = "确定要退出自提柜显示屏吗？",
            sure = "退出",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngCupOut,
                        params = arrayOf("cabinetId" to itemId),
                        onSuccess = {
                            showToast("退出指令发送成功！")
                        }
                    )
            }
        )
    }

    /**
     * 编辑自提柜
     */
    private fun modifyCupboard(item: CupboardData, index: Int) {
        showCupboardDialog(
            defName = item.name,
            defCode = item.cabinetNo,
            defStatus = item.status,
            defTypeId = item.type,
            defTypeName = item.typeName,
            defCount = item.count,
            defNum = item.screenNo.orEmpty(),
            isForced = true,
            onScan = {
                mDialogCode = it

                startActivityEx<ScanActivity>(
                    "mode" to QRType.CUPBOARD,
                    "from" to "pickup"
                )
            },
            onSelect = { tvType, total, screen, typeArr ->
                showListDialog(
                    title = "请选择设备类型",
                    items = getViewModel().mTypeList.map { it.name },
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index

                        typeArr[0] = getViewModel().mTypeList[index].id
                        typeArr[1] = hint

                        total.isVisible = "_EXTEND" in typeArr[0]
                        screen.isVisible = typeArr[0] in "AIR_TOUCh_EXTEND"
                        tvType.text = typeArr[1]
                    }
                )
            },
            onStatus = { tvStatus, statusArr ->
                showListDialog(
                    title = "请选择设备状态",
                    items = getViewModel().mStatusList.map { it.name },
                    index = mStatusIndex,
                    listener = { index, hint ->
                        mStatusIndex = index

                        statusArr[0] = getViewModel().mStatusList[index].id
                        statusArr[1] = hint

                        tvStatus.text = statusArr[1]
                    }
                )
            },
            onSure = { name, code, id, total, screen, status ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngCupUpt,
                        params = arrayOf(
                            "id" to item.id,
                            "name" to name,
                            "cabinetNo" to code,
                            "type" to id,
                            "count" to total,
                            "screenNo" to screen,
                            "status" to status
                        ),
                        onSuccess = {
                            showToast("自提柜修改成功！")

                            item.name = name
                            item.cabinetNo = code
                            item.type = id
                            item.status = status
                            item.count = total
                            item.screenNo = screen
                            item.typeName = when (item.type) {
                                "AIR_BASIC" -> "云柜-普通版"
                                "AIR_BASIC_EXTEND" -> "云柜-普通扩展版"
                                "AIR_TOUCh" -> "云柜-触屏版"
                                "AIR_TOUCh_EXTEND" -> "云柜-触屏扩展版"
                                else -> "云柜V2"
                            }

                            mAdapter.notifyItemChanged(index)
                        }
                    )
            },
            onDismiss = { mDialogCode = null }
        )
    }

    /**
     * 删除自提柜
     */
    private fun deleteCupboard(itemId: String, index: Int) {
        showHintDialog(
            hint = "确定要删除该自提柜设备吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngCupDel,
                        params = arrayOf("ids" to itemId),
                        onSuccess = {
                            showToast("自提柜删除成功！")

                            mList.removeAt(index - 1)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, itemCount - index)
                            }

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 自提柜列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .cupboardList(
                page = index,
                shopId = mPickupId,
                keyWord = "",
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mList.onEach {
                        it as CupboardData
                        it.typeName = when (it.type) {
                            "AIR_BASIC" -> "云柜-普通版"
                            "AIR_BASIC_EXTEND" -> "云柜-普通扩展版"
                            "AIR_TOUCh" -> "云柜-触屏版"
                            "AIR_TOUCh_EXTEND" -> "云柜-触屏扩展版"
                            else -> "云柜V2"
                        }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}